package com.base.controller;

import com.base.comm.CommContent;
import com.base.comm.CommExcel;
import com.base.comm.CommUrls;
import com.base.po.voip.*;
import com.base.service.*;
import com.base.utils.Page;
import com.base.utils.Produce;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 挪车订单
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/admin")
public class index_TrafficCard {
	@Autowired
	private UsersService usersService;
	@Autowired
	private SubscribersService subscribersService;
	@Autowired
	private RewardsService rewardsService;
	@Autowired
	private TrafficCardApplicationService trafficCardApplicationService;
	//读取配置文件
	@Value("${system.file-path}")
	private String filePath;
	// 大王卡订单首页
	@RequestMapping("/trafficCard")
	public ModelAndView index(HttpServletRequest request) throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		/**
		 *  @Date: 2020/4/21 14:05
		 *  @Description:
		 *  如果是admin的则查询全部
		 */ 

		Page page = new Page();
		Users users = usersService.selectByPrimaryKey(adminUserId);
//		if(adminUserId.equals("7dd9a07e-9cef-4702-a165-b7033861c1b7")){
//			adminUserId=null;
//		}

		// 已有订单
		List<TrafficCardApplication> applications = null;
		page.setCurrentPageNo(1);
		if(users.getRole() == 0) {
			page.setRecordTotal(trafficCardApplicationService.countByAll(null, null, null,null, null));
			applications = trafficCardApplicationService.selectByAll(page, null, null, null,null,null);
		}
		if(users.getRole() == 1) {
			page.setRecordTotal(trafficCardApplicationService.countByAll(adminUserId, null, null,null, null));
			applications = trafficCardApplicationService.selectByAll(page, adminUserId, null, null,null,null);
		}
		if(users.getRole() == 2) {
			page.setRecordTotal(trafficCardApplicationService.countByAll(null, adminUserId, null,null,null));
			applications = trafficCardApplicationService.selectByAll(page, null, adminUserId, null,null,null);
		}

		for (TrafficCardApplication application : applications){
			application.setParentid(usersService.selectByPrimaryKey(application.getParentid()).getUsername());
			application.setShopid(usersService.selectByPrimaryKey(application.getShopid()) == null ?
					"未知商家" : usersService.selectByPrimaryKey(application.getShopid()).getUsername());
		}

		request.setAttribute("totlenum", page.getRecordTotal()); // 分页
		request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中
		request.setAttribute("application", applications);
		request.setAttribute("adminUsergrade", adminUsergrade);

		// 设置页面进行跳转
		modelAndView.setViewName("jsp/index_TrafficCard");
		return modelAndView;
	}

	@RequestMapping("/selectTrafficCard")
	public ModelAndView selectTrafficCard(HttpServletRequest request, Integer curPage, String phone, String timeFrom, String timeTo) throws Exception {
		// 设置session缓存
		if (curPage == null) {
			if (request.getSession().getAttribute("curPage") != null) {
				curPage = (Integer) request.getSession().getAttribute("curPage");
			} else {
				curPage = 1;
			}
		}
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		ModelAndView modelAndView = new ModelAndView();
		Page page = new Page();
        Users users = usersService.selectByPrimaryKey(adminUserId);

        String fTimeFrom = null;
		String fTimeTo = null;
		String fPhone = null;
		if(timeFrom !=null && !timeFrom.equals("") && timeTo != null && !timeTo.equals("")) {
			fTimeFrom = timeFrom;
			fTimeTo = timeTo;
		}
		if (phone != null && !phone.equals("")){
			fPhone = phone;
		}

        //已有订单
		List<TrafficCardApplication> applications = null;
        page.setCurrentPageNo(curPage);
		if(users.getRole() == 0) {
			page.setRecordTotal(trafficCardApplicationService.countByAll(null, null, fPhone,fTimeFrom, fTimeTo));
			applications = trafficCardApplicationService.selectByAll(page, null, null, fPhone,fTimeFrom,fTimeTo);
		}
        if(users.getRole() == 1) {
            page.setRecordTotal(trafficCardApplicationService.countByAll(adminUserId, null, fPhone, fTimeFrom, fTimeTo));
			applications = trafficCardApplicationService.selectByAll(page, adminUserId, null, fPhone, fTimeFrom, fTimeTo);
        }
		if(users.getRole() == 1) {
			page.setRecordTotal(trafficCardApplicationService.countByAll(null, adminUserId, fPhone, fTimeFrom, fTimeTo));
			applications = trafficCardApplicationService.selectByAll(page, null, adminUserId, fPhone, fTimeFrom, fTimeTo);
		}

		for (TrafficCardApplication application : applications){
			application.setParentid(usersService.selectByPrimaryKey(application.getParentid()).getUsername());
			application.setShopid(usersService.selectByPrimaryKey(application.getShopid()) == null ?
					"未知商家" : usersService.selectByPrimaryKey(application.getShopid()).getUsername());
		}

		request.setAttribute("totlenum", page.getRecordTotal()); // 分页
		request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中

		// 设置页面进行跳转
		modelAndView.setViewName("jsp/index_TrafficCard");
		request.setAttribute("application", applications);
		request.setAttribute("phone", phone);
		request.setAttribute("timeFrom", timeFrom);
		request.setAttribute("timeTo", timeTo);
		request.setAttribute("adminUsergrade", adminUsergrade);
		return modelAndView;
	}

	@RequestMapping("/activationCard")
	public void activationCard(HttpServletRequest request, HttpServletResponse response, String id) throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		String result = "激活返利异常";

		TrafficCardApplication application = trafficCardApplicationService.selectByPrimaryKey(id);
		application.setIsactivation(1);
		int updateCode = trafficCardApplicationService.updateByPrimaryKeySelective(application);
		if (updateCode == 1){
			List<Subscribers> subscribersList = subscribersService.selectBySub(application.getPhone(), application.getParentid());
			if (!subscribersList.isEmpty()){
				Subscribers subscribers = subscribersList.get(0);
				Double integral = 5.00;// 返利金额
				if (subscribers.getParentid().equals("58162318-deca-4442-8e38-743b7729aa5b")){
					integral = 9.90;
				}
				int activationCode = rewardsService.insert(new Rewards(4, application.getParentid(), subscribers.getId(), subscribers.getId(),
						integral, 1, Produce.getNowDate(), 1));
				if (activationCode == 1){
					result = "激活返利成功";
				}else {
					result = "激活返利失败,返利异常";
				}
			}else {
				result = "激活返利失败,用户异常";
			}
		}else {
			result = "激活返利失败,激活异常";
		}

		out.print(result);
	}

	// 激活信息导入excel 读取
	@RequestMapping("/excelTrafficCard")
	public void excelTrafficCard(HttpServletRequest request, HttpServletResponse response, String file) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		List<TrafficCardApplication> cardApplications = readExcel(request,response,file);

		updateExcelTrafficCard(request, response, cardApplications);
	}

	@RequestMapping("/updateExcelTrafficCard")
	private void updateExcelTrafficCard(HttpServletRequest request, HttpServletResponse response, List<TrafficCardApplication> cardApplications) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();

		if (!cardApplications.isEmpty()){
			for (TrafficCardApplication cardApplication : cardApplications){
				String mobile = cardApplication.getPhone();
				String parentName = cardApplication.getParentid();
				Users users = usersService.selectByUsername(parentName);
				if (users != null){
				    try {
                        String parentId = users.getId();
                        Subscribers sub = subscribersService.selectBySubscribers(mobile, parentId);
                        String id = sub.getId();
                        TrafficCardApplication application = trafficCardApplicationService.selectByPrimaryKey(id);
                        if (application.getIsactivation() == 1){
                            continue;
                        }else {
                            activationCard(request, response, id);
                        }
                    }catch (Exception e){
				        continue;
                    }
                }
			}
		}
	}

	public List<TrafficCardApplication> readExcel(HttpServletRequest request, HttpServletResponse response, String file) throws Exception{
		List<TrafficCardApplication> cardApplications = new ArrayList<>();

		PrintWriter out = response.getWriter();
		if (file == null || CommExcel.EMPTY.equals(file)) {
			out.println("请传入正确的Excel文件");
			return cardApplications;
		} else {
			String postfix = getPostfix(file);
			if (!CommExcel.EMPTY.equals(postfix)) {
				if (CommExcel.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
					cardApplications = readXls(request,response,file);
				} else if (CommExcel.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
					cardApplications = readXlsx(request,response,file);
				}
			} else {
				System.out.println(file + CommExcel.NOT_EXCEL_FILE);
			}
		}

		return cardApplications;
	}

	/**
	 * 读取 Excel 2010
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public List<TrafficCardApplication> readXlsx(HttpServletRequest request, HttpServletResponse response, String file) throws Exception {
		System.out.println(CommExcel.PROCESSING + file);
		InputStream is = new FileInputStream(file);
		@SuppressWarnings("resource")
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
		List<TrafficCardApplication> cardApplications = new ArrayList<>();
		// 读取表格
		for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
			XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
			if (xssfSheet == null) {
				continue;
			}
			// 读取行
			for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
				XSSFRow xssfRow = xssfSheet.getRow(rowNum);
				if (xssfRow != null) {
					TrafficCardApplication cardApplication = new TrafficCardApplication();
					XSSFCell oemUserName = xssfRow.getCell(7);
					XSSFCell activationPhone = xssfRow.getCell(15);
					XSSFCell activationTime = xssfRow.getCell(16);

                    try {
                        String time = getXValue(activationTime);
                        if (time == null || time.equals("")){
                            continue;
                        }
                    }catch (Exception e){
                        continue;
                    }

                    cardApplication.setParentid(getXValue(oemUserName));
                    cardApplication.setPhone(getXValue(activationPhone));
                    cardApplication.setActivationtime(getXValue(activationTime));

					cardApplications.add(cardApplication);
				}
			}
		}

		return cardApplications;
	}

	/**
	 * 读取 Excel 2003-2007
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 */
	public List<TrafficCardApplication> readXls(HttpServletRequest request, HttpServletResponse response, String file) throws IOException, ParseException {
		System.out.println(CommExcel.PROCESSING + file);
		PrintWriter out = response.getWriter();
		InputStream is = new FileInputStream(file);
		@SuppressWarnings("resource")
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
		List<TrafficCardApplication> cardApplications = new ArrayList<>();
		// 读取表格
		for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
			if (hssfSheet == null) {
				continue;
			}
			// 读取行
			for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
				HSSFRow hssfRow = hssfSheet.getRow(rowNum);
				if (hssfRow != null) {
					TrafficCardApplication cardApplication = new TrafficCardApplication();
					HSSFCell oemUserName = hssfRow.getCell(7);
					HSSFCell activationPhone = hssfRow.getCell(15);
					HSSFCell activationTime = hssfRow.getCell(16);

                    try {
                        String time = getHValue(activationTime);
                        if (time == null || time.equals("")){
                            continue;
                        }
                    }catch (Exception e){
                        continue;
                    }

                    cardApplication.setParentid(getHValue(oemUserName));
                    cardApplication.setPhone(getHValue(activationPhone));
                    cardApplication.setActivationtime(getHValue(activationTime));

					cardApplications.add(cardApplication);
				}
			}
		}

		return cardApplications;
	}

	//Excal 2007-2010 取值
	@SuppressWarnings({ "static-access", "deprecation" })
	private String getXValue(XSSFCell xssfRow) {
		if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
			return String.valueOf(xssfRow.getBooleanCellValue());
		} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
			return String.valueOf(xssfRow.getNumericCellValue());
		} else {
			return String.valueOf(xssfRow.getStringCellValue());
		}
	}

	//Excal 2003 取值
	@SuppressWarnings({ "static-access", "deprecation" })
	private String getHValue(HSSFCell hssfCell) {
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			return String.valueOf(hssfCell.getNumericCellValue());
		} else {
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}


	//判断Excel 2003 或者2007-2010
	public static String getPostfix(String file) {
		if (file == null || CommExcel.EMPTY.equals(file)) {
			return CommExcel.EMPTY;
		}
		if (file.contains(CommExcel.POINT)) {
			return file.substring(file.lastIndexOf(CommExcel.POINT) + 1);
		}
		return CommExcel.EMPTY;
	}

    // 重复的卡导出
    public void nonExistentExport(HttpServletRequest request, HttpServletResponse response, String nonExistent) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String file = filePath+"Txt/未注册或不存在手机号.txt";
        try {
            File writeFile = new File(file);
            writeFile.createNewFile(); // 创建新文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(writeFile));
            String[] mobiles = nonExistent.split(",");
            for (String mobile : mobiles) {
                bw.write(mobile + "\r\n"); // \r\n即为换行
            }

            bw.flush(); // 把缓存区内容压入文件
            bw.close(); // 最后记得关闭文件
        } catch (Exception e) {
            e.printStackTrace();
        }

        out.print(CommUrls.Url + "file/Txt/未注册或不存在手机号.txt");
    }
}
